﻿using BUGCOME.Infrastructure.WebExtensions;
using BUGCOME.ServiceCore.Filters;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace BUGCOME.Common.Api.Controllers
{
    /// <summary>
    /// 系统参数配置控制器
    /// 处理参数配置的增删改查
    /// 路由：commonapi/[控制器]/[方法]，分组common
    /// </summary>
    [Route("commonapi/[controller]/[action]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "common")]
    [Verify]
    public class SysConfigController : BaseController
    {
        /// <summary>
        /// 参数配置服务接口
        /// 用于调用业务层逻辑
        /// 依赖注入获取实例
        /// </summary>
        private readonly ISysConfigService _sysConfigService;

        /// <summary>
        /// 构造函数
        /// 初始化参数配置服务
        /// 依赖注入实现实例化
        /// </summary>
        /// <param name="sysConfigService">参数配置服务实现类</param>
        public SysConfigController(ISysConfigService sysConfigService)
        {
            _sysConfigService = sysConfigService;
        }

        /// <summary>
        /// 分页查询参数配置列表
        /// 支持多条件过滤（类型、名称、键、时间）
        /// 需admin:config:list权限
        /// </summary>
        /// <param name="parm">查询参数DTO（含分页和过滤条件）</param>
        /// <returns>分页查询结果</returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:config:list")]
        public async Task<IActionResult> QuerySysConfig([FromBody] SysConfigQueryDto parm)
        {
            var predicate = Expressionable.Create<SysConfig>();
            predicate = predicate.AndIF(!parm.ConfigType.IsEmpty(), m => m.ConfigType == parm.ConfigType);
            predicate = predicate.AndIF(!parm.ConfigName.IsEmpty(), m => m.ConfigName.Contains(parm.ConfigType));
            predicate = predicate.AndIF(!parm.ConfigKey.IsEmpty(), m => m.ConfigKey.Contains(parm.ConfigKey));
            predicate = predicate.AndIF(!parm.BeginTime.IsEmpty(), m => m.CreateTime >= parm.BeginTime);
            predicate = predicate.AndIF(!parm.BeginTime.IsEmpty(), m => m.CreateTime <= parm.EndTime);
            var response = await _sysConfigService.GetPagesAsync(predicate.ToExpression(), parm);
            return Success(response);
        }

        /// <summary>
        /// 查询参数配置详情
        /// 根据ID获取单个参数信息
        /// 需admin:config:query权限
        /// </summary>
        /// <param name="dto">包含配置ID的参数DTO</param>
        /// <returns>单个参数配置的详情信息</returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:config:query")]
        public async Task<IActionResult> GetSysConfig([FromBody] ParmDto<long> dto)
        {
            var response = await _sysConfigService.GetIdAsync(dto.Value);
            return Success(response);
        }

        /// <summary>
        /// 根据键名查询参数值
        /// 供其他服务获取配置值
        /// 允许匿名访问
        /// </summary>
        /// <param name="dto">包含参数键名的参数DTO</param>
        /// <returns>参数对应的配置值（不存在则返回null）</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GetConfigKey([FromBody] ParmDto<string> dto)
        {
            var response = await _sysConfigService.Queryable().FirstAsync(f => f.ConfigKey == dto.Value);
            return Success(response?.ConfigValue);
        }

        /// <summary>
        /// 添加参数配置
        /// 自动填充创建人、时间等信息
        /// 需admin:config:add权限，记日志
        /// </summary>
        /// <param name="parm">新增参数配置DTO</param>
        /// <returns>新增结果（通常为新增记录ID）</returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:config:add")]
        [Log(Title = "参数配置添加", BusinessType = BusinessType.INSERT)]
        public async Task<IActionResult> AddSysConfig([FromBody] SysConfigDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求参数错误");
            }
            var model = parm.Adapt<SysConfig>().ToCreate(HttpContext);
            var result = await _sysConfigService.InsertSysConfigAsync(model);
            return Success(result);
        }

        /// <summary>
        /// 更新参数配置
        /// 自动填充更新人、时间等信息
        /// 需admin:config:update权限，记日志
        /// </summary>
        /// <param name="parm">更新参数配置DTO</param>
        /// <returns>更新结果（影响的行数）</returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:config:update")]
        [Log(Title = "参数配置修改", BusinessType = BusinessType.UPDATE)]
        public async Task<IActionResult> UpdateSysConfig([FromBody] SysConfigDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求实体不能为空");
            }
            var model = parm.Adapt<SysConfig>().ToUpdate(HttpContext);
            var response = await _sysConfigService.UpdateAsync(
                w => w.ConfigId == model.ConfigId,
                it => new SysConfig
                {
                    ConfigName = model.ConfigName,
                    ConfigKey = model.ConfigKey,
                    ConfigValue = model.ConfigValue,
                    ConfigType = model.ConfigType,
                    UpdateBy = model.UpdateBy,
                    UpdateTime = model.UpdateTime,
                    Remark = model.Remark
                });
            return Success(response);
        }

        /// <summary>
        /// 删除参数配置
        /// 支持批量删除，系统内置参数不可删
        /// 需admin:config:remove权限，记日志
        /// </summary>
        /// <param name="dto">包含ID字符串的参数DTO（多ID用逗号分隔）</param>
        /// <returns>删除结果（影响的行数）</returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "admin:config:remove")]
        [Log(Title = "参数配置删除", BusinessType = BusinessType.DELETE)]
        public async Task<IActionResult> DeleteSysConfig([FromBody] ParmDto<string> dto)
        {
            int[] idsArr = Tools.SplitIntArray(dto.Value);
            if (idsArr.Length <= 0)
            {
                return ToResponse(ApiResult.Error($"删除失败Id 不能为空"));
            }
            int sysCount = await _sysConfigService.CountAsync(s => s.ConfigType == "Y" && idsArr.Contains(s.ConfigId));
            if (sysCount > 0)
            {
                return ToResponse(ApiResult.Error($"删除失败Id： 系统内置参数不能删除！"));
            }
            var response = await _sysConfigService.DeleteAsync(idsArr);
            return Success(response);
        }
    }
}